﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;


namespace eFrameWork.Customs.Base
{
    public partial class Excel_Templates : System.Web.UI.Page
    {
        public string UserArea = "Application";
        public string act = eParameters.Request("act");
        public string ModelID = eParameters.Request("ModelID");
        public string AppItem = eParameters.Request("AppItem");
        public eUser user;
        public eModel model;


        private string basePath = "";//当前目录
        public string path = eParameters.QueryString("path");
        string aspxFile = eBase.getAspxFileName();
        string type = eParameters.QueryString("type");
        public string ajax = eParameters.QueryString("ajax");
        public eExtensionsList allowExts = new eExtensionsList(".xls.xlsx.zip");//.csv
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser(eBase.getUserArea(UserArea));
            user.Check();

            eModelInfo customModel = new eModelInfo(user);
            model = customModel.Model;
            

            basePath = eRunTime.excelTemplatesPath;
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
            if (path.IndexOf("..") > -1) path = "";//禁止越权上级目录
            if (path.Length > 0) path = path.toUrlFormat();
            if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);
            if (!Directory.Exists(basePath + path.toLocalFormat())) path = "";
            if (path.Length > 0) basePath += path.toLocalFormat() + "\\";


            #region 安全性
            if (act.Length > 0 && (Request.UrlReferrer == null || Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()))
            {
                //Response.Write("访问未被许可!");
                //Response.End();
            }
            #endregion
            #region 操作
            string filepath = "";
            string oldname = "";
            string newname = "";
            string reurl = "";
            eFileResult result;
            JsonData json;
            DataTable tb;
            string ext = "";
            string name = eParameters.QueryString("name");//文件名，文件夹名
            if (name.Contains("..")) eRunTime.endError("文件名无效!");
            switch (act)
            {
                case "reload"://OK
                    #region 重新加载
                    JsonData jd = new JsonData();
                    jd.Add("success", "1");
                    jd.Add("errcode", "0");
                    jd.Add("body", getFiles());
                    //jd.Add("table", eBase.encode(eListControl.getControlHTML()));
                    Response.Write(jd.ToJson());
                    Response.End();
                    #endregion
                    break;
                case "upload"://OK
                    #region 上传文件
                    StringBuilder sb = new StringBuilder();
                    JsonData files = JsonMapper.ToObject("[]");
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile file = Request.Files[i];
                        ext = file.FileName.fileExtension();
                        filepath = basePath + file.FileName.File();
                        result = file.safeSaveAs(filepath, allowExts);
                        if (!result.Success) eRunTime.endError(result.Message);
                        #region 文件返回JSON
                        JsonData item = new JsonData();
                        item.Add("name", file.FileName);
                        item.Add("ext", ext);
                        item.Add("size", file.Size());
                        item.Add("time", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
                        item.Add("url", filepath.toUrl());
                        files.Add(item);
                        #endregion
                        getFileHTML(sb, file.FileName);
                    }
                    if (ajax == "true")
                    {
                        //eResult.Success("文件上传成功!");
                        json = new JsonData();
                        json.Add("errcode", "0");
                        json.Add("message", "上传成功!");
                        json["files"] = files;
                        eResult.WriteJson(json);
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    //Response.Redirect(reurl, true);
                    Response.Write(sb.ToString());
                    Response.End();
                    #endregion
                    break;
                case "save"://OK
                    #region 保存
                    filepath = basePath + name;
                    string value = eParameters.Form("value");
                    //value = value.Replace("0x\\r\\n", "\r\n");
                    value = eBase.decode(value);
                    value = value.Replace("\n", "\r\n");
                    result = eFileHelper.save(filepath, value);
                    if (!result.Success) eRunTime.endError(result.Message);
                    eResult.Success("保存成功!");
                    #endregion
                    break;
                case "edit"://OK
                    #region 读取
                    filepath = basePath + name;
                    result = eFileHelper.read(filepath);
                    if (!result.Success) eRunTime.endError(result.Message);
                    string content = result.Content;
                    content = HttpUtility.HtmlEncode(content);
                    JsonData obj = new JsonData();
                    obj["success"] = 1;
                    obj["errcode"] = "0";
                    obj["message"] = "读取成功!";
                    obj["value"] = content;
                    eResult.WriteJson(obj);
                    #endregion
                    break;
                case "newfile"://OK
                    #region 新建文件
                    filepath = basePath + name;
                    result = eFileHelper.create(filepath);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件创建成功!");
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "newfolder"://OK
                    #region 添加文件夹
                    result = eFolderHelper.create(basePath + name);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件夹创建成功!");    
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "rename"://OK
                    #region 重命名文件、文件夹
                    oldname = basePath + eParameters.QueryString("oldname");
                    newname = basePath + eParameters.QueryString("newname");
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.rename(oldname, newname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        result = eFileHelper.rename(oldname, newname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "重命名成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "oldname");
                    reurl = eParameters.removeQuery(reurl, "newname");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "bak"://OK
                    #region 备份文件、文件夹
                    oldname = basePath + name;
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.backup(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        result = eFileHelper.backup(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "备份成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "del"://OK
                    #region 删除文件、文件夹
                    string tmpPath = basePath + name;
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.remove(tmpPath);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        result = eFileHelper.remove(tmpPath);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true") eResult.Success("文件" + (type == "1" ? "夹" : "") + "删除成功!");
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "zip": //OK
                    #region 压缩
                    oldname = basePath + name;
                    if (type == "1")//文件夹
                    {
                        newname = oldname + ".zip";
                        //eZipHelper.folderToZip(oldname, newname);
                        result = eZipHelper.folderToZip(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        eFileInfo fi = new eFileInfo(oldname);
                        newname = fi.Path + fi.Name + ".zip";
                        //eZipHelper.fileToZip(oldname, newname);
                        result = eZipHelper.fileToZip(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true") eResult.Success("文件" + (type == "1" ? "夹" : "") + "压缩成功!");
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "unzip"://OK
                    #region 解压
                    oldname = basePath + name;
                    //new FastZip().ExtractZip(oldname, basePath, "");//覆盖
                    //result = eZipHelper.extract(oldname, basePath);
                    result = eZipHelper.extract(oldname);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件解压成功!");
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "download"://OK
                    #region 下载
                    if (Request.Path != Request.CurrentExecutionFilePath) Response.Redirect(Request.CurrentExecutionFilePath + Request.Url.Query, true);                    
                    oldname = basePath + name;
                    result= eFileHelper.download(oldname);
                    if (!result.Success) eRunTime.endError(result.Message);   
                    #endregion
                    break;
                case ""://OK
                    #region 列表
                    litBody.Text = List();
                    #endregion
                    break;
            }
            #endregion
        }

        private void getFileHTML(StringBuilder sb, string name)
        {          
            string _path = basePath + name;
            FileInfo info = new FileInfo(_path);
            eFileInfo fi = new eFileInfo(name);
            sb.Append("<a ext=\"" + fi.fileExtension + "\" href=\"javascript:;\" onclick=\"viewFile('" + _path.toVirtualUrl() + "');\" _href=\"" + aspxFile + "?act=download" + (AppItem.Length > 0 ? "&AppItem=" + AppItem : "&ModelID=" + ModelID) + "&path=" + (path.Length > 0 ? path + "/" : path) + "&name=" + Server.UrlEncode(name) + "\" targe3t=\"_blank\" class=\"copypath\" onmousedown=\"contextmenu(event,this,2,'" + name + "');\" title=\"" + name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.LastWriteTime) + "&#10;大小：" + info.Size() + "\">\r\n");
            sb.Append("<dl>\r\n");
            //sb.Append("<dt><img src=\"../images/excel.png\" /></dt>\r\n");
            sb.Append("<dt class=\"excel\"></dt>\r\n");
            sb.Append("<dd>" + name + "</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("</a>\r\n");
        }
        private string getFiles()
        {
            StringBuilder sb = new StringBuilder();

            eDirectoryInfo edinfo = new eDirectoryInfo(basePath);
            foreach (DirectoryInfo folder in edinfo.GetDirectories())
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&path=" + (path.Length > 0 ? path + "/" : path) + folder.Name.ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + folder.Name + "');\" title=\"" + folder.Name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.LastWriteTime) + "&#10;大小：" + folder.Size() + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + folder.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }
            foreach (FileInfo file in edinfo.GetFiles())
            {
                if (!allowExts.Contains(file.Extension)) continue;
                getFileHTML(sb, file.Name);
            }
            sb.Append("<div class=\"clear\"></div>\r\n");
            return sb.ToString();
        }
        private string List()
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append("<div>当前位置：");
           
            if (path.Length > 0)
            {
                //sb.Append("<a href=\"" + aspxFile + "?modelid=" + ModelID + "\">根目录</a>");
                litNav.Text = "<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + model.ModelInfo["MC"].ToString() + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">根目录</a>";
                string[] arr = path.Split("/".ToCharArray());
                string tmp = "";
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i > 0) tmp += "/";
                    tmp += arr[i];
                    if (i == arr.Length - 1)
                    {
                        //sb.Append(" / " + arr[i]);
                    }
                    else
                    {
                        //sb.Append(" / <a href=\"" + aspxFile + "?modelid=" + ModelID + "&path=" + tmp + "\">" + arr[i] + "</a>");
                    }
                    litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&path=" + tmp + "\">" + arr[i] + "</a>";
                }
            }
            else
            {
                //sb.Append("根目录");
                litNav.Text = "<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + model.ModelInfo["MC"].ToString() + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">根目录</a>";
            }

            if (model.Power["new"] || model.Power["upload"])
            {
                sb.Append("<div class=\"filemanage_tool\" style=\"margin-tottom:8px;\">");
                if (model.Power["new"])
                {
                    sb.Append("<a href=\"javascript:;\" class=\"ico addfolder\" onclick=\"file_newFolder();\" title=\"新建文件夹\"></a>");
                    //sb.Append("<a href=\"javascript:;\" class=\"ico addfile\" onclick=\"file_newFile();\" title=\"新建文件\"></a>");
                }
                if (model.Power["upload"])
                {
                    sb.Append("<a href=\"javascript:;\" class=\"ico upload\" title=\"上传文件\">");
                    //sb.Append("<input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" badexts=\"" + eConfig.getPreventExtensions() + "\" accept=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel\" onchange=\"file_upload(this);\" multiple=\"multiplt\" />");
                    sb.Append("<input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" posturl=\"auto\" allowexts=\"" + allowExts.ToString() + "\" preventexts=\"" + eConfig.PreventExtensions.ToString() + "\" accept=\"" + allowExts.ToString(",") + "\" callback=\"autoupload_callback\" onchange=\"autoupload_change(this);\" multiple=\"multiplt\" />");
                    sb.Append("</a>");
                }
                sb.Append("</div>");
            }

            sb.Append("<div id=\"filemanage_files\" class=\"filemanage_files\" oncontextmenu=\"return false;\">");            
            sb.Append(getFiles());
            sb.Append("</div>");
            return sb.ToString();
        }
    }
}